import os
import json
from ..config.webapp import WxappConfig
from aiohttp import ClientSession
class WxappUtils(object):

    def __init__(self, config: WxappConfig=WxappConfig()):
        self.config: WxappConfig = config

    async def jscode2session(self, code):
        """
        登录
        :url https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
        :param code: 小程序登录时获取的 code
        :return:
        """
        url = 'https://api.weixin.qq.com/sns/jscode2session?appid={APPID}&secret={SECRET}&js_code={JSCODE}&grant_type=authorization_code'
        url = url.format(**{
            'APPID': self.config.appid,
            'SECRET': self.config.secret,
            'JSCODE': code,
        })
        print("url",url)
        async with ClientSession() as session:
            async with session.request('GET',url,headers={"Accept":"*"}) as response:
                data= await response.text()
                return json.loads(data)
        # return resp.json()
    async def getUnlimitedQRCode(self, page:str, scene:str):
        """
        获取小程序二维码
        :url https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html
        :param page: 跳转小程序页面
        :param scene: 场景值
        :return:
        """
        await self.getAccessToken()
        url = f"https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={self.access_token}"
        params = json.dumps({
            "scene": scene,
            "page": page,
            "env_version":os.environ['ENVIRONMENT'],
            "check_path": False,
        })
        print(params)
        async with ClientSession() as session:
            async with session.request('post',url,data=params,headers={"Accept":"*","Content-Type":"application/json"}) as response:
                res =await response.content.read()
                return res
            


    async def getAccessToken(self):
        """
        获取小程序 access_token
        :url https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html
        :return:
        """

        url = "https://api.weixin.qq.com/cgi-bin/stable_token"
        
        params = json.dumps({
            "grant_type": "client_credential",
            "appid": self.config.appid,
            "secret": self.config.secret,
        } )

        async with ClientSession() as session:
            async with session.request('post',url,data=params,headers={"Accept":"*","Content-Type":"application/json"}) as response:
                res = await response.text()
                data = json.loads(res)
                if "errcode" not in data:
                    self.access_token = data['access_token']
